﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy1 : MonoBehaviour
{
    //属性值-移动速度
    private float moveSleep = 3f;

    //子弹的旋转方向，这里子弹的方向采用旋转而不是替换图片
    private Vector3 bulletEulerAngles;

    // 子弹攻击的CD
    private float attackCD = 0f;


    // 引用变量

    //精灵渲染器
    private SpriteRenderer spriteRenderer;
    //坦克的朝向数组，此处需要使用 public 才能在GUI中显示
    public Sprite[] tankDirection;
    //敌人子弹引用
    public GameObject enemyBullet;
    //爆炸引用
    public GameObject explosionPrefab;


    private void Awake()
    {
        //初始化渲染器
        spriteRenderer = GetComponent<SpriteRenderer>();
    }


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void FixedUpdate()
    {

        PlayerMove();

        //CD大于0.4 就能发射
        if (attackCD > 0.4f)
        {
            Attack();
        }
        else
        {
            attackCD += Time.fixedDeltaTime;
        }
    }

    //坦克攻击方法
    private void Attack()
    {
        // 按下空格
        if (Input.GetKey(KeyCode.Space))
        {
            //创建实例，（实例对象，位置，方向），子弹的角度：坦克的角度+旋转的角度
            Instantiate(enemyBullet, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
            //CD归零
            attackCD = 0;
        }
    }


    // 坦克移动方法
    private void PlayerMove()
    {
        //按WSAD 或者方向键执行移动
        //垂直上下移动
        float v = Input.GetAxisRaw("Vertical");
        transform.Translate(Vector3.up * v * moveSleep * Time.fixedDeltaTime, Space.World);
        if (v > 0)
        {
            //向上
            spriteRenderer.sprite = tankDirection[0];
            bulletEulerAngles = new Vector3(0, 0, 0);
        }
        else if (v < 0)
        {
            //向下
            spriteRenderer.sprite = tankDirection[2];
            bulletEulerAngles = new Vector3(0, 0, -180);
        }
        if (v != 0)
        {
            //禁止坦克斜着走，优先上下移动
            return;
        }

        //水平左右移动
        float h = Input.GetAxisRaw("Horizontal");
        transform.Translate(Vector3.right * h * moveSleep * Time.fixedDeltaTime, Space.World);
        if (h < 0)
        {
            //向左
            spriteRenderer.sprite = tankDirection[3];
            bulletEulerAngles = new Vector3(0, 0, 90);
        }
        else if (h > 0)
        {
            //向右
            spriteRenderer.sprite = tankDirection[1];
            bulletEulerAngles = new Vector3(0, 0, -90);
        }

    }

    //敌人死亡方法
    private void EnemyDie()
    {

        //爆炸动画
        Instantiate(explosionPrefab, transform.position, transform.rotation);

        //销毁
        Destroy(gameObject);

    }
}
